package com.thotran.applockplus.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DbHelper {

	public static DbHelper mDHelper = null;

	public static SQLiteDatabase mDB;

	public static final String DATABASE_NAME = "applockplus.db";

	public static final int DATABASE_VERSION = 1;

	public static final String TABLE_NAME = "applockplus";

	public static final String NAME_APP = "name";

	public static final String PACKAGE_APP = "package";

	public static final String CHECKED_APP = "checked";

	public static final String ID_APP = "id";

	public static DbHelper getInstance(Context context) {

		if (mDHelper == null) {
			synchronized (DbHelper.class) {
				mDHelper = new DbHelper(context);
			}
		}

		return mDHelper;
	}

	public DbHelper(Context context) {
		DatabaseHelper mDatabaseHelper = new DatabaseHelper(context,
				DATABASE_NAME, null, DATABASE_VERSION);
		mDB = mDatabaseHelper.getWritableDatabase();
	}

	public class DatabaseHelper extends SQLiteOpenHelper {

		public DatabaseHelper(Context context, String name,
				CursorFactory factory, int version) {
			super(context, name, factory, version);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			String sql = "  create table " + TABLE_NAME + " ( " + ID_APP
					+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + NAME_APP
					+ " TEXT, " + PACKAGE_APP + " TEXT )  ";
			db.execSQL(sql);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

		}

	}

	public int insertAppLock(String name, String package_app) {
		int id = 0;
		ContentValues mContentValues = new ContentValues();
		mContentValues.put(NAME_APP, name);
		mContentValues.put(PACKAGE_APP, package_app);
		id = (int) mDB.insert(TABLE_NAME, null, mContentValues);
		return id;
	}

	public void updateAppLock() {

	}

	public void deleteAppLock(String packageName) {
		mDB.delete(TABLE_NAME, " " + PACKAGE_APP + "=?",
				new String[] { packageName });
	}

	public boolean checkExistsApp(String packageName) {
		boolean result = false;
		int count = 0;
		String sql = " select count(*) from " + TABLE_NAME + " where "
				+ PACKAGE_APP + "='" + packageName + "' ";
		Cursor mCursor = mDB.rawQuery(sql, null);
		if (mCursor != null) {
			while (mCursor.moveToNext()) {
				count = mCursor.getInt(0);
			}
		}
		if (count == 1)
			result = true;
		return result;
	}

}
